<?php
/**
 * Created by PhpStorm.
 * User: priestll
 * Date: 20-7-14
 * Time: 下午3:05
 */

namespace App\Biz;


use App\Model\AwardsRecordModel;
use App\Model\StageUserModel;

use EasySwoole\ORM\DbManager;
use priestll\easyswoole\biz\BaseBiz;
use priestll\easyswoole\queue\Job;
use priestll\easyswoole\queue\Queue;


class AwardsBiz extends BaseBiz
{

    const TYPE_OBJECT = 1;//实物
    const TYPE_MONEY = 2;//现金红包
    const TYPE_SCORE = 3;//积分
    const TYPE_FLOW = 4;//话费流量
    const TYPE_NONE = 5;//没有奖品


    public function cache($user_id)
    {
        $job = new Job();
        $job->setMethod('awards');
        $job->setJobData($user_id);
        Queue::getInstance()->producer()->push($job);
    }

    public function awards($user_id)
    {

        $res['type'] = self::TYPE_NONE;
        $res['name'] = '谢谢参与';

        $stageUserModel = StageUserModel::create();

        $stageUser = $stageUserModel->getByWhere(['user_id' => $user_id]);

        if (!$stageUser) {
            $this->sendSuccess($user_id, $res);
            return ;
        }

        $stage = $stageUser->stage();

        if ($stageUser->power < $stage->power) {
             $this->sendFail($user_id, '能量值不足');
            //$this->sendFail($user_id, 'power off');
            return ;
        }

        $award = $stage->awards();

        if ($award->stock <= 0) {
            $this->sendSuccess($user_id, $res);
            return ;
        }

        $rand = rand(0, 100);

        if ($rand > $award->probability) {
            $this->sendSuccess($user_id, $res);
            return ;
        }
        //中奖
        $awardsRecordModel = AwardsRecordModel::create();
        $db = DbManager::getInstance();
        try {
            //开启事务
            $db->startTransaction();
            $awardsRecordModel->data([
                'user_id' => $user_id,
                'award_id' => $award->id,
                'award_name' => $award->name,
                'status' => 1,
                'is_send' => 0,
            ])->save();

            $award->stock -- ;
            $award->update();
            //提交事务
            $db->commit();
            $res['type'] = $award->type;
            $res['name'] = $award->name;
            $res['img'] = $award->img;
        } catch (\Throwable  $e) {
            //回滚事务
            $db->rollback();
            //var_dump($e);
        } finally {

            $this->sendSuccess($user_id, $res);
            return ;
        }

    }


}